package yzm_demo;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

public class AESUtils {
    private static String aesKey = "2dc82e0dc1bcd2d5";

    /**
     * AES算法128位加密
     * 
     * @param cleartext
     * @return
     */
    public String encrypt(String cleartext) {
        try {
            for(int i=cleartext.length();i<16;i++){
				cleartext = cleartext+'\0';
			}
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            SecretKeySpec skeySpec = new SecretKeySpec(aesKey.getBytes("UTF-8"), "AES");
            cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
            byte[] encrypted = cipher.doFinal(cleartext.getBytes("UTF-8"));
            //return Base64.getEncoder().encodeToString(encrypted);
            return parseByte2HexStr(encrypted);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * AES算法128位解密
     * 
     * @param encrypMsg
     * @return
     */
    public String decrypt(String encrypMsg) {
        try {
            Cipher cipher = Cipher.getInstance("AES");
            SecretKeySpec keySpec = new SecretKeySpec(aesKey.getBytes(), "AES");
            cipher.init(Cipher.DECRYPT_MODE, keySpec);
            byte[] decbbdt = cipher.doFinal(parseHexStr2Byte(encrypMsg));
            String str=new String(decbbdt, "UTF-8").replace("\0", "");
            return str;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    	/**
	 * 将二进制转换成16进制
	 * 
	 * @param buf
	 * @return
	 */
	private static String parseByte2HexStr(byte buf[]) {
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < buf.length; i++) {
			String hex = Integer.toHexString(buf[i] & 0xFF);
			if (hex.length() == 1) {
				hex = '0' + hex;
			}
			sb.append(hex.toUpperCase());
		}
		return sb.toString();
	}

	/**
	 * 将16进制转换为二进制
	 * 
	 * @param hexStr
	 * @return
	 */
	private static byte[] parseHexStr2Byte(String hexStr) {
		if (hexStr.length() < 1)
			return null;
		byte[] result = new byte[hexStr.length() / 2];
		for (int i = 0; i < hexStr.length() / 2; i++) {
			int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1), 16);
			int low = Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 + 2), 16);
			result[i] = (byte) (high * 16 + low);
		}
		return result;
	}
	public static void main(String[] args) {
        String content = "FIE3";
		System.out.println("加密之前：" + content);

		// 加密
        AESUtils e1 = new AESUtils();
		String encrypt = e1.encrypt(content);
		System.out.println("加密后的内容：" + encrypt);

		// 解密
        AESUtils e2 = new AESUtils();
		String decrypt = e2.decrypt(encrypt);
		System.out.println("解密后的内容：" + decrypt);


	}
}